import React, { useCallback, useEffect, useRef, useState } from 'react';
import Label from '@/components/Label';
import {
  AutoComplete,
  AutoCompleteProps,
  Button,
  Checkbox,
  Input,
  Table,
  Tabs,
  TabsProps,
} from 'antd';
import { SvgIcon } from '../icon';
import NotData from '../NotData';
import PersonnelModal from '../personnel-modal/personnel-modal';
import useModal from '@/hooks/use-modal/useModal';
import ModalsBoxContent from '../modals/ModalsBoxContent';
import orgService from '@/api/services/orgService';
import {
  DatasetTypeEnum,
  GetDatasetList,
  GetDatasetNl2sqlList,
  GetDatasetTreeItem,
  GetTargetTree,
  GetTargetTreeOriginalTarget,
  GetTargetTreeResources,
  TargetUsers,
} from '@/common/types';
import TreeUI from './components/TreeUI';
import LeftTreeUI from './components/LeftTreeUI';
import DatasetAndFunctionTreeUI from './components/DatasetAndFunctionTreeUI';
import UserTreeUI from './components/UserTreeUI';
import { debounce, truncate } from 'lodash';
import { CircleLoading } from '../loading';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { AppStatusEnum, AppType } from '@/common/app/constants';

type SearchResult = {
  label: string;
  value: string[]; // id数组
  data: GetTargetTree; //原数据
};

const QaPermissionContent = () => {
  const modal = useModal('update');

  const { configurations, appDetail, isInOrchestrationPage } = useOrchestrationStore();

  //  是否配置知识库
  const isDisableDataset =
    configurations?.find((config) => config.name === 'disable_dataset')?.default_value === '1' ||
    false;

  // 是否配置数据接口
  const isEnableFunctionCalling = configurations?.find(
    (config) => config.name === 'enable_function_calling',
  );

  const isEnableNl2sql = !isInOrchestrationPage || configurations?.find(
    (config) => config.name === 'enable_nl2sql',
  );

  const isEnableNl2sqlDataset =
    configurations?.find((config) => config.name === 'enable_nl2sql_dataset')?.default_value === '1' ||
    false;

  // 知识库列表
  const [datasetList, setDatasetList] = useState<GetDatasetList[]>([]);

  // 数据接口列表
  const [functionList, setFunctionList] = useState<GetDatasetList[]>([]);

  // NL2SQL列表
  const [nl2sqlList, setNl2sqlList] = useState<GetDatasetNl2sqlList[]>([]);

  // 禁选数据
  const [disabledData, setDisabledData] = useState<TargetUsers[]>([]);

  // 默认数据
  const [defaultValue, setDefaultValue] = useState<any[]>([]);

  // 用户树
  const [userTree, setUserTree] = useState<GetTargetTree[]>([]);

  // 选择用户树
  const [selectUserTree, setSelectUserTree] = useState<GetTargetTree>();

  // 知识库树
  const [datasetTree, setDatasetTree] = useState<GetDatasetTreeItem[]>([]);

  // 数据接口树
  const [functionTree, setFunctionTree] = useState<GetDatasetTreeItem[]>([]);

  // NL2SQL树
  const [nl2sqlTree, setNl2sqlTree] = useState<GetDatasetTreeItem[]>([]);

  // 开启子项
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  // 开启树节点子项
  const [expandedTreeUIKeys, setExpandedTreeUIKeys] = useState<string[]>([]);

  // 选中的知识库与数据接口
  const [selectDatasetAndFunction, setSelectDatasetAndFunction] = useState<GetDatasetTreeItem>();

  // 知识库与数据接口视图树
  const [expandedDatasetAndFunction, setExpandedDatasetAndFunction] = useState<string[]>([]);

  // 开启用户树子项
  const [expandedUserTreeUI, setExpandedUserTreeUI] = useState<string[]>([]);

  // 展开全部
  const [treeUIOpenAll, setTreeUIOpenAll] = useState(false);

  // 展开全部用户
  const [treeUserUIOpenAll, setTreeUserUIOpenAll] = useState(false);

  // tabs数据
  const [tabsItem, setTabsItem] = useState<TabsProps['items']>([
    {
      key: '1',
      label: '知识库',
    },
    ...(!isInOrchestrationPage || isEnableFunctionCalling) ? [{
      key: '2',
      label: '数据接口',
    }] : [],
    ...((isEnableNl2sql || isEnableNl2sqlDataset) ? [{
      key: '3',
      label: '数据库问答',
    }] : []),
  ]);

  const tabMap: Record<string, DatasetTypeEnum> = {
    '1': DatasetTypeEnum.dataset,
    '2': DatasetTypeEnum.function,
    '3': DatasetTypeEnum.database,
  };

  const [tabsValue, setTabsValue] = useState<string>('1');

  const [labelKey, setLabelKey] = useState<string>('1');

  const [treeUIOptions, setTreeUIOptions] = useState<AutoCompleteProps['options']>([]);

  const [pendingScrollId, setPendingScrollId] = useState<string>('');

  const [pendingScrollUserId, setPendingScrollUserId] = useState<string>('');

  const [pendingScorllUserRightId, setPendingScorllUserRightId] = useState<string>('');

  const [userOptions, setUserOptions] = useState<AutoCompleteProps['options']>([]);

  const [datasetLoading, setDatasetLoading] = useState<boolean>(false);

  const functionBox = useRef<HTMLDivElement>(null);

  const userBox = useRef<HTMLDivElement>(null);

  const userRightBox = useRef<HTMLDivElement>(null);

  const [searchValue, setSearchValue] = useState<string>('');

  // 过滤后的用户树
  const [filteredUserTree, setFilteredUserTree] = useState<GetTargetTree[]>([]);

  // 获取appId
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';

  useEffect(() => {
    if (appId) {
      getDataset();
      getFunction();
      getNl2sql();
    }
  }, [appId]);

  // 初始化过滤后的用户树
  useEffect(() => {
    setFilteredUserTree(userTree);
  }, [userTree]);

  useEffect(() => {
    setSearchValue("");
  }, [labelKey]);

  useEffect(() => {
    if (labelKey === '1') {
      getRole();
      getPolicies();
    } else {
      getDatasetTree();
    }
  }, [labelKey]);

  // 遍历 children，筛选包含搜索关键字的节点及其子节点
  const filterDatasetList = (list: GetDatasetList[], searchText: string): GetDatasetList[] => {
    return list
      .map((item) => {
        if (item.children && item.children.length > 0) {
          const filteredChildren = filterDatasetList(item.children, searchText);

          // if (
          //   item.name.toLowerCase().includes(searchText.toLowerCase()) ||
          //   filteredChildren.length > 0
          // ) {
          //   return { ...item, children: filteredChildren };
          // }

          // 如果父级包含搜索文本，保留所有子级
          if (item.name.toLowerCase().includes(searchText.toLowerCase())) {
            return { ...item, children: item.children };
          }
          // 否则只保留匹配的子级
          if (filteredChildren.length > 0) {
            return { ...item, children: filteredChildren };
          }

          return null;
        }
        if (item.name.toLowerCase().includes(searchText.toLowerCase())) {
          return item;
        }
        return null;
      })
      .filter(Boolean) as GetDatasetList[];
  };

  // 获取知识库
  const getDataset = (searchText: string = '') => {
    orgService
      .getDataset({
        appId: appId,
        type: DatasetTypeEnum.dataset,
        // searchText,
      })
      .then((res) => {
        if (searchText) {
          setDatasetList(filterDatasetList(res.list, searchText));
        } else {
          setDatasetList(res.list);
        }
      });
  };

  // 获取数据接口
  const getFunction = (searchText: string = '') => {
    orgService
      .getDataset({
        appId: appId,
        type: DatasetTypeEnum.function,
        // searchText,
      })
      .then((res) => {
        if (searchText) {
          setFunctionList(res.list.filter((item) => item.name.toLowerCase().includes(searchText.toLowerCase())));
        } else {
          setFunctionList(res.list);
        }
      });
  };

  // 获取NL2SQL数据
  const getNl2sql = (searchText: string = '') => {
    orgService
      .getDatasetNl2sql({
        appId: appId,
        // searchText,
      })
      .then((res) => {
        if (searchText) {
          setNl2sqlList(res.list.filter((item) => item.name.toLowerCase().includes(searchText.toLowerCase())));
        } else {
          setNl2sqlList(res.list);
        }
      });
  };

  // 获取用户信息
  const getRole = () => {
    orgService.getRole(appId).then((res) => {
      const result = res.find((item) => item.code === 'admin');
      setDisabledData(result?.target_users ?? []);
    });
  };

  // 获取选中信息
  const getPolicies = () => {
    orgService.getPolicies({ app_id: appId }).then((res) => {
      const targets = res.map((item) => {
        return {
          target_id: item.target.target_id,
          target_type: item.target.target_type,
          target_name: item.target.target_name,
        };
      });

      orgService
        .getTargetTree({
          app_id: appId,
          targets: targets,
        })
        .then((tree) => {
          if (tree.target_tree) {
            setUserTree([tree.target_tree]);
          } else {
            setUserTree([]);
          }

          if (tree.target_tree) {
            const expandedList = [...expandedKeys, tree.target_tree.target_id];
            const result = new Set([...expandedList]);
            setExpandedKeys([...result]);
          }

          let temp = undefined;

          if (tree.target_tree) {
            temp = getUserSelect([tree.target_tree], selectUserTree?.target_id);
          }

          // if (tree.original_targets.some((item) => item.target_id === selectUserTree?.target_id)) {
          //   temp = getUserSelect([tree.target_tree], selectUserTree?.target_id || '');
          // }
          setSelectUserTree(temp);
        });

      const result = res.map((item) => {
        return {
          id: item.target.target_id,
          name: item.target.target_name,
          resources: item.resources,
          type: item.target.target_type,
        };
      });
      setDefaultValue(result);
    });
  };

  // 获取知识库/接口视图
  const getDatasetTree = () => {
    setDatasetLoading(true);
    orgService
      .getDatasetTree({ appId: appId })
      .then((res) => {
        const datasetList: GetDatasetTreeItem[] = [];
        const functionList: GetDatasetTreeItem[] = [];

        res.list.map((item) => {
          if (item.type === DatasetTypeEnum.function) {
            functionList.push(item);
          } else {
            datasetList.push(item);
          }
        });
        setDatasetTree(datasetList);
        setFunctionTree(functionList);

        let temp = getDatasetSelect(res.list, selectDatasetAndFunction?._id || '');
        setSelectDatasetAndFunction(temp);
      })
      .finally(() => {
        setDatasetLoading(false);
      });

    orgService
      .getDatasetNl2sql({ appId: appId })
      .then((res) => {
        const nl2sqlList: GetDatasetTreeItem[] = [];

        res.list.map((item) => {
          nl2sqlList.push(item as unknown as GetDatasetTreeItem);
        });
        setNl2sqlTree(nl2sqlList);
      })
      .finally(() => {
        setDatasetLoading(false);
      });
  };

  // 向上查找节点
  const patchTree = (oldTree: GetTargetTree[], newTree: GetTargetTree[]): GetTargetTree[] => {
    const oldMap = new Map<string, GetTargetTree>();
    const treeToMap = (arr: GetTargetTree[]) => {
      arr.forEach((node) => {
        oldMap.set(node.target_id, node);
        if (node.childrens) {
          treeToMap(node.childrens);
        }
      });
    };
    treeToMap(oldTree);

    // 根据 newTree 构造结果，尽可能复用 oldTree 节点
    function build(newNodes: GetTargetTree[]): GetTargetTree[] {
      return newNodes.map((node) => {
        const oldNode = oldMap.get(node.target_id);
        const resultNode = oldNode || { ...node, childrens: [] };
        resultNode.target_id = node.target_id;
        resultNode.childrens = build(node.childrens || []);
        // 如果有其它属性也要同步，可以补充同步代码
        // 例如 resultNode.name = node.name;
        return resultNode;
      });
    }

    return build(newTree);
  };

  // 提交用户信息
  const handlePersonnelSubmit = (value: any[]) => {
    const result = value.map((item) => ({
      target_id: item.id,
      target_type: item.type,
      target_name: item.name,
    }));

    orgService
      .getTargetTree({
        app_id: appId,
        targets: result,
      })
      .then((res) => {
        const result = patchTree(userTree, res.target_tree ? [res.target_tree] : []);
        const defaultValueList = res.original_targets.map((item) => ({
          id: item.target_id,
          type: item.target_type,
          name: item.target_name,
        }));
        setDefaultValue(defaultValueList);
        setUserTree(result);
        modal.update.close();

        let temp = undefined;
        if (res.original_targets.some((item) => item.target_id === selectUserTree?.target_id)) {
          temp = getUserSelect([res.target_tree], selectUserTree?.target_id || '');
        }
        setSelectUserTree(temp);
      });
  };

  // 点击用户树
  const handleClickUserTree = (value: GetTargetTree, type: boolean = false) => {
    setSelectUserTree(value);
    if (type) {
      const result = expandedKeys.includes(value.target_id);

      if (result) {
        setExpandedKeys(expandedKeys.filter((item) => item !== value.target_id));
      } else {
        setExpandedKeys([...expandedKeys, value.target_id]);
      }
    }
  };

  // 点击内容树
  const handleClickTreeUITree = (value: GetDatasetList) => {
    const result = expandedTreeUIKeys.includes(value._id);
    if (result) {
      setExpandedTreeUIKeys(expandedTreeUIKeys.filter((item) => item !== value._id));
    } else {
      setExpandedTreeUIKeys([...expandedTreeUIKeys, value._id]);
    }
  };

  // 点击知识库与数据接口视图树
  const handleClickDatasetAndFunctionTree = (value: GetDatasetTreeItem, type: boolean = false) => {
    setSelectDatasetAndFunction(value);

    if (type) {
      const result = expandedDatasetAndFunction.includes(value._id);

      if (result) {
        setExpandedDatasetAndFunction(
          expandedDatasetAndFunction.filter((item) => item !== value._id),
        );
      } else {
        setExpandedDatasetAndFunction([...expandedDatasetAndFunction, value._id]);
      }
    }
  };

  // 替换节点数据
  const replaceTreeNode = (tree: GetTargetTree[], newTree: GetTargetTree): GetTargetTree[] => {
    return tree.map((node) => {
      if (node.target_id === newTree.target_id) {
        return newTree;
      }

      return {
        ...node,
        childrens: replaceTreeNode(node.childrens || [], newTree),
      };
    });
  };

  // 删除指定id并扁平化树形结构
  const removeAndFlattenTree = (tree: GetDatasetList[], removeId: string) => {
    const result: GetDatasetList[] = [];

    function traverse(nodes: GetDatasetList[]) {
      for (const node of nodes) {
        if (node._id === removeId) continue; // 跳过要去除的节点
        // 先把自身加入
        result.push({ ...node, children: [] });
        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          traverse(node.children);
        }
      }
    }

    traverse(tree);
    return result;
  };

  // 点击选项
  const handleClicTreeUI = (type: string, know?: GetDatasetList) => {
    // 为全选
    if (type === 'all') {
      handleClickTreeUIAll();
      return;
    }

    if (tabsValue === '1') {
      handleClickKnow(know);
      return;
    }

    if (tabsValue === '2') {
      handleClickFunction(know);
      return;
    }

    if (tabsValue === '3') {
      handleClickNl2sql(know);
      return;
    }
  };

  // 点击全选
  const handleClickTreeUIAll = () => {
    // 判断是否存在所有知识库与所有数据接口的权限
    const selectUserAll = selectUserTree?.resources.find(
      (item) => item.resource_type === '*' && item.resource_id === '*',
    );

    // 存在所有知识库与所有数据接口的权限
    if (selectUserAll !== undefined) {
      let temp = {
        ...selectUserTree,
        resources: [
          {
            action: 'qa',
            resource_id: '*',
            resource_name: '',
            // resource_type: tabsValue === '1' ? DatasetTypeEnum.function : DatasetTypeEnum.dataset,
            resource_type: tabMap[tabsValue],
          },
        ],
      };
      handleSetUserTree(temp as GetTargetTree);
      return;
    }

    /* ----------------------------------------------- */

    // 当前为知识库页面
    if (tabsValue === '1') {
      // 判断是否为所有知识库
      const selectUserDataset = selectUserTree?.resources.find(
        (item) => item.resource_type === DatasetTypeEnum.dataset && item.resource_id === '*',
      );
      // const userResources = selectUserTree?.resources ?? [];
      const userResources =
        selectUserTree?.resources.filter(
          (item) => item.resource_type !== DatasetTypeEnum.dataset && item.resource_type !== DatasetTypeEnum.folder,
        ) || [];

      let temp = {
        ...selectUserTree,
        resources: [
          ...userResources,
          {
            action: 'qa',
            resource_id: '*',
            resource_name: '',
            resource_type: DatasetTypeEnum.dataset,
          },
        ],
      };

      if (selectUserDataset !== undefined) {
        temp = {
          ...selectUserTree,
          resources: userResources.filter(
            (item) => item.resource_type !== DatasetTypeEnum.dataset && item.resource_id === '*',
          ),
        };
      }

      handleSetUserTree(temp as GetTargetTree);
      return;
    }

    if (tabsValue === '3') {
      const selectUserDataset = selectUserTree?.resources.find(
        (item) => item.resource_type === DatasetTypeEnum.database && item.resource_id === '*',
      );
      const userResources =
        selectUserTree?.resources.filter(
          (item) => item.resource_type !== DatasetTypeEnum.database
        ) || [];

      let temp = {
        ...selectUserTree,
        resources: [
          ...userResources,
          {
            action: 'qa',
            resource_id: '*',
            resource_name: '',
            resource_type: DatasetTypeEnum.database,
          },
        ],
      };

      if (selectUserDataset !== undefined) {
        temp = {
          ...selectUserTree,
          resources: userResources.filter(
            (item) => item.resource_type !== DatasetTypeEnum.database && item.resource_id === '*',
          ),
        };
      }

      handleSetUserTree(temp as GetTargetTree);
      return;
    }

    /* ----------------------------------------------- */

    // 当前为数据接口页面
    const selectUserDataset = selectUserTree?.resources.find(
      (item) => item.resource_type === DatasetTypeEnum.function && item.resource_id === '*',
    );
    // const userResources = selectUserTree?.resources ?? [];
    const userResources =
      selectUserTree?.resources.filter((item) => item.resource_type !== DatasetTypeEnum.function) || [];

    let temp = {
      ...selectUserTree,
      resources: [
        ...userResources,
        {
          action: 'qa',
          resource_id: '*',
          resource_name: '',
          resource_type: DatasetTypeEnum.function,
        },
      ],
    };

    if (selectUserDataset !== undefined) {
      temp = {
        ...selectUserTree,
        resources: userResources.filter(
          (item) => item.resource_type !== DatasetTypeEnum.function && item.resource_id === '*',
        ),
      };
    }

    handleSetUserTree(temp as GetTargetTree);
    return;
  };

  // 查找父级
  const findParent = (
    tree: GetDatasetList[],
    id: string,
    parent: GetDatasetList | null = null,
  ): GetDatasetList | null => {
    for (const node of tree) {
      if (node._id === id) return parent;
      if (node.children && node.children.length > 0) {
        const result = findParent(node.children, id, node);
        if (result) return result;
      }
    }
    return null;
  };

  // 查找父节点信息
  const findUserParent = (tree: GetTargetTree[], targetId: string): GetTargetTree | null => {
    for (let node of tree) {
      if (node.childrens && node.childrens.length > 0) {
        // 如果node的children有目标id的节点
        const found = node.childrens.find((child) => child.target_id === targetId);
        if (found) {
          return node;
        } else {
          // 递归在子节点里继续查找
          const deeper = findUserParent(node.childrens, targetId);
          if (deeper) return deeper;
        }
      }
    }
    return null;
  };

  // 向上查找父节点并格式化信息
  const getParentAll = (id: string, type: boolean = false): GetTargetTreeResources[] => {
    // 找到父节点
    const parentNode = findParent(datasetList, id);
    if (!parentNode) return [];

    // 收集当前父节点下所有children（不包括自身）
    const siblingResources = parentNode.children
      .filter((item) => item._id !== id)
      .map((item) => ({
        resource_type: item.type,
        resource_id: item._id,
        resource_name: item.name,
        action: 'qa',
      }));

    // 如果父节点是顶层，递归终止
    if (parentNode.parent_id === null) {
      let parentList: any[] = [];

      if (!type) {
        parentList = datasetList
          .filter((item) => item._id !== parentNode._id)
          .map((item) => ({
            resource_type: item.type,
            resource_id: item._id,
            resource_name: item.name,
            action: 'qa',
          }));
      }

      return [...siblingResources, ...parentList];
    }

    // 递归向上收集
    return [...siblingResources, ...getParentAll(parentNode._id, type)];
  };

  // 获取树形中所有子项的id
  const findChildrenIds = (tree: GetDatasetList[], id: string): string[] => {
    function dfs(node: GetDatasetList): string[] {
      return (node.children ?? []).reduce<string[]>(
        (acc, child) => [...acc, child._id, ...dfs(child)],
        [],
      );
    }
    for (const node of tree) {
      if (node._id === id) {
        return dfs(node);
      }
      if (node.children) {
        const found = findChildrenIds(node.children, id);
        if (found.length > 0) return found;
      }
    }
    return [];
  };

  // 获取树形中所有父项的id
  const findParentIds = (tree: GetDatasetList[], id: string, path: string[] = []): string[] => {
    for (const node of tree) {
      if (node._id === id) {
        return path; // 当前路径即为所有父级id
      }
      if (node.children) {
        const found = findParentIds(node.children, id, [...path, node._id]);
        if (found.length > 0) return found;
      }
    }
    return [];
  };

  // 扁平化数组筛选
  const filterFaltArray = (
    flatArray: GetTargetTreeResources[],
    excludeIds: string[],
  ): GetTargetTreeResources[] => {
    return flatArray.filter((item) => !excludeIds.includes(item.resource_id));
  };

  // 是否父级存在选中
  const selectTree = (list: GetTargetTreeResources[], id: string) => {
    const parent = findParent(datasetList, id);
    console.log('parent', parent);

    if (!parent || !parent._id) return false;
    if (list.some((item) => item.resource_id === parent._id)) return true;
    return selectTree(list, parent._id);
  };

  // 去除子项
  const getChildrenSelect = (list: GetTargetTreeResources[], id: string) => {
    const childrenIds = findChildrenIds(datasetList, id);
    const parentIds = findParentIds(datasetList, id);

    const filtered = filterFaltArray(list, [...childrenIds, ...parentIds, id]);
    return filtered;
  };

  const handleClickKnow = (value?: GetDatasetList) => {
    if (!value) {
      return;
    }

    // 查找是否存在这一项
    const findKnowStatus = selectUserTree?.resources.find((item) => item.resource_id === value._id);

    let tempResources: GetTargetTree;

    // 存在这一项
    if (findKnowStatus) {
      tempResources = {
        ...selectUserTree!,
        resources: selectUserTree?.resources.filter((item) => item.resource_id !== value._id) || [],
      };
    } else {
      // 全选状态
      const valueAll = selectUserTree?.resources.find(
        (item) => item.resource_type === '*' && item.resource_id === '*',
      );

      // 全选知识库状态
      const datasetStatus = selectUserTree?.resources.find(
        (item) => item.resource_type === DatasetTypeEnum.dataset && item.resource_id === '*',
      );

      if (valueAll || datasetStatus) {
        let resource: GetTargetTreeResources[] = valueAll
          ? [
            {
              resource_type: DatasetTypeEnum.function,
              resource_id: '*',
              resource_name: '',
              action: 'qa',
            },
          ]
          : selectUserTree?.resources.filter(
            (item) => item.resource_type !== DatasetTypeEnum.dataset && item.resource_type !== DatasetTypeEnum.folder,
          ) || [];

        // 向上查找节点
        let parent: GetTargetTreeResources[] = [];
        // getParentAll(value._id)

        if (value.parent_id) {
          parent = getParentAll(value._id);
        } else {
          parent = datasetList
            .filter((item) => item._id !== value._id)
            .map((item) => ({
              resource_type: item.type,
              resource_id: item._id,
              resource_name: item.name,
              action: 'qa',
            }));
        }

        tempResources = {
          ...selectUserTree!,
          resources: [...resource, ...parent],
        };
      } else {
        // 不为全选，不为知识库全选状态
        // 只剩下选中父级中存在选中的情况和普通选中状态的情况
        const result = getParentAll(value._id, true);

        const parentSelect = selectTree(selectUserTree?.resources || [], value._id);

        // if (result.length > 0 && parentSelect) {
        if (parentSelect) {
          const temp = getChildrenSelect(selectUserTree?.resources || [], value._id);
          tempResources = {
            ...selectUserTree!,
            resources: [...temp, ...result],
          };
        } else {
          const temp = getChildrenSelect(selectUserTree?.resources || [], value._id);
          tempResources = {
            ...selectUserTree!,
            resources: [
              ...temp,
              {
                action: 'qa',
                resource_id: value._id,
                resource_name: value.name,
                resource_type: value.type,
              },
            ],
          };
        }
      }
    }

    console.log('tempResources', tempResources);

    handleSetUserTree(tempResources);
  };

  // 在数据接口页面点击
  const handleClickFunction = (value?: GetDatasetList) => {
    if (value === undefined) {
      return;
    }

    // 判断是否为数据接口全选类型
    const selectUserFunction = selectUserTree?.resources.find(
      (item) => item.resource_type === DatasetTypeEnum.function && item.resource_id === '*',
    );

    if (selectUserFunction !== undefined) {
      const removeTree = removeAndFlattenTree(functionList, value?._id as string);

      const newDataset =
        selectUserTree?.resources.filter((item) => item.resource_type !== DatasetTypeEnum.function) || [];

      const functionListFlatten = removeTree.map((item) => ({
        action: 'qa',
        resource_id: item._id,
        resource_name: item.name,
        resource_type: item.type,
      }));

      const temp = {
        ...selectUserTree,
        resources: [...functionListFlatten, ...newDataset],
      };

      handleSetUserTree(temp as GetTargetTree);
      return;
    }

    const selectUserResources = selectUserTree?.resources.find(
      (item) => item.resource_id === value?._id,
    );

    let tempResources: GetTargetTree;

    if (selectUserResources) {
      tempResources = {
        ...selectUserTree!,
        resources:
          selectUserTree?.resources.filter((item) => item.resource_id !== value?._id) ?? [],
      };
    } else {
      tempResources = {
        ...selectUserTree!,
        resources: [
          ...(selectUserTree?.resources ?? []),
          {
            action: 'qa',
            resource_id: value?._id as string,
            resource_name: value?.name as string,
            resource_type: value?.type as string,
          },
        ],
      };
    }

    handleSetUserTree(tempResources);
    return;
  };

  // 在数据接口页面点击
  const handleClickNl2sql = (value?: GetDatasetList) => {
    if (value === undefined) {
      return;
    }

    // 判断是否为数据接口全选类型
    const selectUserFunction = selectUserTree?.resources.find(
      (item) => item.resource_type === DatasetTypeEnum.database && item.resource_id === '*',
    );

    if (selectUserFunction !== undefined) {
      const removeTree = removeAndFlattenTree(functionList, value?._id as string);

      const newDataset =
        selectUserTree?.resources.filter((item) => item.resource_type !== DatasetTypeEnum.database) || [];

      const listFlatten = removeTree.map((item) => ({
        action: 'qa',
        resource_id: item._id,
        resource_name: item.name,
        resource_type: item.type,
      }));

      const temp = {
        ...selectUserTree,
        resources: [...listFlatten, ...newDataset],
      };

      handleSetUserTree(temp as GetTargetTree);
      return;
    }

    const selectUserResources = selectUserTree?.resources.find(
      (item) => item.resource_id === value?._id,
    );

    let tempResources: GetTargetTree;

    if (selectUserResources) {
      tempResources = {
        ...selectUserTree!,
        resources:
          selectUserTree?.resources.filter((item) => item.resource_id !== value?._id) ?? [],
      };
    } else {
      tempResources = {
        ...selectUserTree!,
        resources: [
          ...(selectUserTree?.resources ?? []),
          {
            action: 'qa',
            resource_id: value?._id as string,
            resource_name: value?.name as string,
            resource_type: value?.type as string,
          },
        ],
      };
    }

    handleSetUserTree(tempResources);
    return;
  };

  // 格式化树形结构
  const handleSetUserTree = (newTree: GetTargetTree) => {
    const result = replaceTreeNode(userTree, newTree);
    orgService
      .setPoliciesTarget({
        app_id: appId,
        statement: {
          target: {
            target_id: newTree.target_id,
            target_type: newTree.target_type,
            target_name: newTree.target_name,
          },
          resources: newTree.resources,
        },
      })
      .then(() => {
        setSelectUserTree(newTree);
        setUserTree(result);
      });
  };

  const handleTabsValue = (key: string) => {
    setTabsValue(key);
  };

  // 处理继承以后的数据类型
  const filterInheritResource = (list: GetTargetTreeResources[]): GetTargetTreeResources[] => {
    if (list.length === 0) {
      return [];
    }
    let result: GetTargetTreeResources[] = [];

    const selectAll = list.find((item) => item.resource_id === '*' && item.resource_type === '*');

    const selectList = list.find(
      (item) =>
        item.resource_id === '*' &&
        item.resource_type === (tabsValue === '1' ? DatasetTypeEnum.dataset : tabsValue === '2' ? DatasetTypeEnum.function : DatasetTypeEnum.database),
    );

    if (selectAll) {
      result = list.filter((item) => item.resource_id !== '*' && item.resource_type !== '*');
      result.push({
        action: 'qa',
        resource_id: '*',
        resource_name: '',
        resource_type: tabsValue === '1' ? DatasetTypeEnum.dataset : tabsValue === '2' ? DatasetTypeEnum.function : DatasetTypeEnum.database,
      });
    } else if (selectList) {
      result = list.filter((item) =>
        tabsValue === '1'
          ? item.resource_type !== DatasetTypeEnum.dataset && item.resource_type !== DatasetTypeEnum.folder
          : tabsValue === '2' ? item.resource_type !== DatasetTypeEnum.function : item.resource_type !== DatasetTypeEnum.database,
      );

      result.push({
        action: 'qa',
        resource_id: '*',
        resource_name: '',
        resource_type: tabsValue === '1' ? DatasetTypeEnum.dataset : tabsValue === '2' ? DatasetTypeEnum.function : DatasetTypeEnum.database,
      });
    } else {
      result = list;
    }

    return result;
  };

  // 继承父级
  const handleInherit = () => {
    const parent = findUserParent(userTree, selectUserTree?.target_id as string);
    if (parent === null) {
      return;
    }

    // const parentResource = parent.resources.filter((item) =>
    //   tabsValue !== '1'
    //     ? item.resource_type !== DatasetTypeEnum.dataset && item.resource_type !== DatasetTypeEnum.folder
    //     :  item.resource_type !== DatasetTypeEnum.function,
    // );

    const parentResource = parent.resources.filter((item) => {
      if (tabsValue == '1') {
        return item.resource_type == DatasetTypeEnum.dataset || item.resource_type == DatasetTypeEnum.folder;
      } else if (tabsValue == '2') {
        return item.resource_type == DatasetTypeEnum.function;
      } else {
        return item.resource_type == DatasetTypeEnum.database;
      }
    });

    const union = Array.from(
      new Map(
        [...(selectUserTree?.resources || []), ...(parentResource || [])].map((obj) => [
          obj.resource_id,
          obj,
        ]),
      ).values(),
    );

    const result = filterInheritResource(union);

    handleSetUserTree({
      ...selectUserTree!,
      resources: result,
    });
  };

  // 切换labdel
  const handleChangeLabel = (options: { key: React.Key; value: string }) => {
    setLabelKey(options.key as string);
  };

  // 展开用户树
  const handleClickUserTreeUIExpandedKeys = (value: GetTargetTree) => {
    const result = expandedUserTreeUI.includes(value.target_id);

    if (result) {
      setExpandedUserTreeUI(expandedUserTreeUI.filter((item) => item !== value.target_id));
    } else {
      setExpandedUserTreeUI([...expandedUserTreeUI, value.target_id]);
    }
  };

  // 点击用户树
  const handleClickUserTreeUI = (type: string, value?: GetTargetTree) => {
    if (type === 'all') {
      const result = defaultValue.map((item) => ({
        target_id: item.id,
        target_name: item.name,
        target_type: item.type,
      }));
      handleSetUserTreeAll(result);
      return;
    }

    handleSetUserTreeList(value as GetTargetTree);
  };

  // 更新节点
  const updateTargets = (
    oldTargets: { target_id: string; target_type: string; target_name: string }[],
    newTree: { target_id: string; target_type: string; target_name: string },
  ) => {
    const exists = oldTargets.some((t) => t.target_id === newTree.target_id);
    if (exists) {
      // 存在则移除
      return oldTargets.filter((t) => t.target_id !== newTree.target_id);
    } else {
      // 不存在则添加
      return [
        ...oldTargets,
        {
          target_id: newTree.target_id,
          target_type: newTree.target_type,
          target_name: newTree.target_name,
        },
      ];
    }
  };

  const getUserSelect = (
    value: GetTargetTree[],
    id: string | undefined,
  ): GetTargetTree | undefined => {
    if (!id) return undefined;

    for (const item of value) {
      if (item.target_id === id) {
        return item;
      }
      if (item.childrens && item.childrens.length > 0) {
        const found = getUserSelect(item.childrens, id);
        if (found) {
          return found;
        }
      }
    }
    return undefined;
  };

  const getDatasetSelect = (
    value: GetDatasetTreeItem[],
    id: string,
  ): GetDatasetTreeItem | undefined => {
    for (const item of value) {
      if (item._id === id) {
        return item;
      }
      if (item.children && item.children.length > 0) {
        const found = getDatasetSelect(item.children, id);
        if (found) {
          return found;
        }
      }
    }
    return undefined;
  };

  // 格式化用户树
  const replaceUserTreeNode = (
    tree: GetDatasetTreeItem[] | GetDatasetNl2sqlList[],
    newTree: GetTargetTree,
  ): any[] => {
    return tree.map((node) => ({
      ...node,
      targets:
        node._id === selectDatasetAndFunction?._id
          ? updateTargets(node.targets || [], newTree)
          : node.targets,
      children:
        node.children && node.children.length ? replaceUserTreeNode(node.children, newTree) : [],
    }));
  };

  const handleSetUserTreeList = (newTree: GetTargetTree) => {
    let temp = selectDatasetAndFunction?.targets || [];
    const exists = temp.some((t) => t.target_id === newTree.target_id);
    if (exists) {
      temp = temp.filter((item) => item.target_id !== newTree.target_id);
    } else {
      temp = [
        ...temp,
        {
          target_id: newTree.target_id,
          target_type: newTree.target_type,
          target_name: newTree.target_name,
        },
      ];
    }
    const result = { ...selectDatasetAndFunction!, targets: temp };

    orgService
      .getResource({
        app_id: appId,
        statement: {
          resource: {
            resource_type: selectDatasetAndFunction?.type as string,
            resource_id: selectDatasetAndFunction?._id as string,
            resource_name: selectDatasetAndFunction?.name as string,
            action: 'qa',
          },
          targets: temp,
        },
      })
      .then((res) => {
        const status =
          selectDatasetAndFunction?.type === DatasetTypeEnum.dataset ||
          selectDatasetAndFunction?.type === DatasetTypeEnum.folder;

        const isNl2sql = selectDatasetAndFunction?.type === DatasetTypeEnum.database;

        const repalceUser = replaceUserTreeNode(
          status ? datasetTree : isNl2sql ? nl2sqlTree : functionTree,
          newTree,
        );

        if (status) {
          setDatasetTree(repalceUser);
        } else if (isNl2sql) {
          setNl2sqlTree(repalceUser);
        } else {
          setFunctionTree(repalceUser);
        }

        setSelectDatasetAndFunction(result);
      });
  };

  const replaceNodeTargetsById = (
    tree: GetDatasetTreeItem[],
    nodeId: string,
    newTargets: GetTargetTree[],
  ): GetDatasetTreeItem[] => {
    return tree.map((node) => {
      if (node._id === nodeId) {
        // 找到节点，返回替换过targets的新对象
        return {
          ...node,
          targets: newTargets,
          children: node.children ? replaceNodeTargetsById(node.children, nodeId, newTargets) : [],
        };
      }
      // 没找到，递归处理下层children
      return {
        ...node,
        children: node.children ? replaceNodeTargetsById(node.children, nodeId, newTargets) : [],
      };
    });
  };

  const handleSetUserTreeAll = (
    value: {
      target_id: string;
      target_name: string;
      target_type: string;
    }[],
  ) => {
    const idSetB = new Set(selectDatasetAndFunction?.targets.map((item) => item.target_id));
    const defaultStatus = defaultValue.every((item) => idSetB.has(item.id));

    let list = value.map((item) => ({
      target_id: item.target_id,
      target_type: item.target_type,
      target_name: item.target_name,
    }));

    if (defaultStatus) {
      list = [];
    }

    const result = { ...selectDatasetAndFunction!, targets: list };

    const status =
      selectDatasetAndFunction?.type === DatasetTypeEnum.dataset || selectDatasetAndFunction?.type === DatasetTypeEnum.folder;

    const isNl2sql = selectDatasetAndFunction?.type === DatasetTypeEnum.database;

    orgService
      .getResource({
        app_id: appId,
        statement: {
          resource: {
            resource_type: selectDatasetAndFunction?.type as string,
            resource_id: selectDatasetAndFunction?._id as string,
            resource_name: selectDatasetAndFunction?.name as string,
            action: 'qa',
          },
          targets: list,
        },
      })
      .then((res) => {
        const findData = replaceNodeTargetsById(
          status ? datasetTree : isNl2sql ? nl2sqlTree : functionTree,
          selectDatasetAndFunction?._id as string,
          list,
        );

        if (status) {
          setDatasetTree(findData);
        } else if (isNl2sql) {
          setNl2sqlTree(findData);
        } else {
          setFunctionTree(findData);
        }
        setSelectDatasetAndFunction(result);
      });
  };

  const handleSearch = (value: string, tab: string) => {
    if(tab === '1'){
      getDataset(value)
    }
    if(tab === '2'){
      getFunction(value)
    }
    if(tab === '3'){
      getNl2sql(value)
    }
    // if (tabsValue === '3') {
    //   orgService
    //     .getDatasetNl2sql({
    //       appId: appId,
    //       searchText: value,
    //     })
    //     .then((res) => {
    //       const result = res.list.map((item) => ({ label: item.name, value: item.id }));
    //       setTreeUIOptions(result);
    //     });
    // } else {
    //   orgService
    //     .getDatasetTree({
    //       appId: appId,
    //       type: tabsValue === '1' ? DatasetTypeEnum.dataset : DatasetTypeEnum.function,
    //       searchText: value,
    //     })
    //     .then((res) => {
    //       // setTreeUIOptions()
    //       const result = res.list.map((item) => ({ label: item.path, value: item.pathId }));
    //       console.log('result', result);
    //       setTreeUIOptions(result);
    //       // console.log(res);
    //     });
    // }
  };

  const handleSearchFn = useCallback(
    debounce((text: string, tabsValue: string) => handleSearch(text, tabsValue), 500),
    [],
  );

  useEffect(() => {
    setSearchValue('')
    handleSearchFn('', tabsValue)
  }, [tabsValue]);

  const handleSelect: AutoCompleteProps['onSelect'] = (_, option) => {
    if (option.value) {
      if (tabsValue === '1') {
        const newArr = new Set([...expandedTreeUIKeys, ...(option.value || [])]);
        setExpandedTreeUIKeys([...newArr]);
      }

      const last = option.value[option.value.length - 1];
      setPendingScrollId(last);
    }
  };

  useEffect(() => {
    if (!pendingScrollId) return;

    const dom = document.querySelector(`[data-id="${pendingScrollId}"]`);

    if (dom instanceof HTMLElement) {
      const offsetTop = dom.offsetTop;
      rollTreeUI(offsetTop);
    }

    setPendingScrollId('');
  }, [expandedTreeUIKeys, pendingScrollId]);

  const rollTreeUI = (top: number) => {
    if (functionBox.current) {
      setTimeout(() => {
        const listElement = functionBox.current;

        listElement?.scrollTo({
          top: top, // 目标位置
          behavior: 'smooth', // 平滑滚动
        });
      }, 50);
    }
  };

  // 过滤用户树，保留匹配的节点及其父节点
  const filterUserTree = (tree: GetTargetTree[], searchText: string): GetTargetTree[] => {
    const lowerText = searchText.toLowerCase();
    
    const filterNode = (node: GetTargetTree): GetTargetTree | null => {
      // 检查当前节点是否匹配
      const isMatch = node.target_name.toLowerCase().includes(lowerText);
      
      // 递归过滤子节点
      let filteredChildren: GetTargetTree[] = [];
      if (node.childrens && node.childrens.length > 0) {
        filteredChildren = node.childrens
          .map(child => filterNode(child))
          .filter((child): child is GetTargetTree => child !== null);
      }
      
      // 如果当前节点匹配或有匹配的子节点，则保留该节点
      if (isMatch || filteredChildren.length > 0) {
        return {
          ...node,
          childrens: filteredChildren,
        };
      }
      
      return null;
    };
    
    return tree
      .map(node => filterNode(node))
      .filter((node): node is GetTargetTree => node !== null);
  };

  const handleUserSearch = (value: string) => {
    setSearchValue(value);
    
    if (!value.trim()) {
      setFilteredUserTree(userTree);
      setUserOptions([]);
      return;
    }

    // 过滤用户树
    const filteredTree = filterUserTree(userTree, value);
    setFilteredUserTree(filteredTree);
    
    // 设置AutoComplete选项
    const result = searchTreeAndReturnPaths(userTree, value);
    setUserOptions(result);
  };

  // 树形搜索，返回符合条件的所有拼接路径
  const searchTreeAndReturnPaths = (
    tree: GetTargetTree[],
    text: string,
    pathNames: string[] = [],
    pathIds: string[] = [],
  ): SearchResult[] => {
    const result: SearchResult[] = [];
    const lowerText = text.toLowerCase();

    for (const node of tree) {
      const nextNames = [...pathNames, node.target_name];
      const nextIds = [...pathIds, node.target_id];
      // 匹配（忽略大小写）
      if (node.target_name.toLowerCase().includes(lowerText)) {
        result.push({
          label: nextNames.join('/'),
          value: nextIds,
          data: node,
        });
      }
      // 递归
      if (node.childrens && node.childrens.length) {
        result.push(...searchTreeAndReturnPaths(node.childrens, text, nextNames, nextIds));
      }
    }
    return result;
  };

  const handleUserSearchFn = useCallback(
    debounce((text: string) => handleUserSearch(text), 500),
    [userTree],
  );

  const handleUserSelect: AutoCompleteProps['onSelect'] = (_, option) => {
    const value = option.value as string[];

    if (labelKey === '1') {
      const newArr = new Set([...expandedKeys, ...value]);
      setExpandedKeys([...newArr]);
      setSelectUserTree(option.data);
      const last = value && value.length > 0 ? value[value.length - 1] : '';
      setPendingScrollUserId(last);
    }

    const newArr = new Set([...expandedUserTreeUI, ...value]);
    setExpandedUserTreeUI([...newArr]);
    const last = value && value.length > 0 ? value[value.length - 1] : '';
    setPendingScorllUserRightId(last);
  };

  const rollUserTreeUI = (top: number) => {
    if (userBox.current) {
      setTimeout(() => {
        const listElement = userBox.current;

        listElement?.scrollTo({
          top: top, // 目标位置
          behavior: 'smooth', // 平滑滚动
        });
      }, 50);
    }
  };

  useEffect(() => {
    if (!pendingScrollUserId) return;

    const dom = document.querySelector(`[data-user-id="${pendingScrollUserId}"]`);

    if (dom instanceof HTMLElement) {
      const offsetTop = dom.offsetTop;
      rollUserTreeUI(offsetTop);
    }

    setPendingScrollUserId('');
  }, [expandedTreeUIKeys, pendingScrollUserId]);

  const rollUserRightTreeUI = (top: number) => {
    if (userRightBox.current) {
      setTimeout(() => {
        const listElement = userRightBox.current;

        listElement?.scrollTo({
          top: top, // 目标位置
          behavior: 'smooth', // 平滑滚动
        });
      }, 50);
    }
  };

  useEffect(() => {
    if (!pendingScorllUserRightId) return;

    const dom = document.querySelector(`[data-tree-id="${pendingScorllUserRightId}"]`);

    if (dom instanceof HTMLElement) {
      const offsetTop = dom.offsetTop;
      rollUserRightTreeUI(offsetTop);
    }

    setPendingScrollUserId('');
  }, [expandedTreeUIKeys, pendingScorllUserRightId]);

  const handleTreeUIOpen = () => {
    if (treeUIOpenAll) {
      setExpandedTreeUIKeys([]);
      setTreeUIOpenAll(false);
    } else {
      const keyList = getTreeChildren(datasetList, 'children', '_id');
      setExpandedTreeUIKeys(keyList);
      setTreeUIOpenAll(true);
    }
  };

  const handleTreeUserUIOpen = () => {
    if (treeUserUIOpenAll) {
      // setExpandedUserTreeUI([]);
      setExpandedUserTreeUI([]);

      setTreeUserUIOpenAll(false);
    } else {
      const keyList = getTreeChildren(userTree, 'childrens', 'target_id');
      setExpandedUserTreeUI(keyList);
      // setExpandedTreeUIKeys(keyList);
      setTreeUserUIOpenAll(true);
    }
  };

  const getTreeChildren = (tree: any, key: string, id: string) => {
    let ids: string[] = [];
    tree.map((node) => {
      if (node[key] && Array.isArray(node[key]) && node[key].length > 0) {
        ids.push(node[id]);
        ids = ids.concat(getTreeChildren(node[key], key, id));
      }
    });
    return ids;
  };

  return (
    <>
      <div className="flex h-full w-full gap-4">
        <div
          className={`rounded-lg bg-[#F7F8FA66] p-6 pr-0 ${appDetail?.appType != AppType.fusion && !isDisableDataset ? 'w-[332px]' : 'w-full'
            }`}
        >
          <div className="mb-2 pr-6">
            {appDetail?.appType != AppType.fusion && !isDisableDataset && (
              <Label
                options={[
                  {
                    key: '1',
                    value: '人/组织视图',
                  },
                  {
                    key: '2',
                    value: '知识库视图',
                  },
                ]}
                onChange={handleChangeLabel}
                value={labelKey}
              />
            )}

            {labelKey === '1' && (
              <div
                className={`flex ${appDetail?.appType != AppType.fusion && !isDisableDataset
                  ? 'flex-col'
                  : 'flex-row-reverse items-center justify-between'
                  }`}
              >
                <div className="relative">
                  <AutoComplete
                    placeholder="搜索人员"
                    // suffix={}
                    onSearch={handleUserSearchFn}
                    options={userOptions}
                    onSelect={handleUserSelect}
                    className={
                      appDetail?.appType != AppType.fusion && !isDisableDataset
                        ? '!mb-2 !mt-4 w-full'
                        : 'w-[184px]'
                    }
                  />
                  <div
                    className="absolute right-2 -translate-y-1/2"
                    style={{
                      top:
                        appDetail?.appType != AppType.fusion && !isDisableDataset
                          ? 'calc(50% + 3px)'
                          : 'calc(50% - 1px)',
                    }}
                  >
                    <SvgIcon icon="work-ic6" size={16} color="text-text-4" />
                  </div>
                </div>
                <Button
                  className={`!border-[#1B6DFA] !text-[#1B6DFA] ${appDetail?.appType != AppType.fusion && !isDisableDataset ? 'w-full' : ''
                    }`}
                  onClick={modal.update.open}
                >
                  编辑可问答人员/组织
                </Button>
              </div>
            )}
          </div>

          {labelKey === '1' ? (
            <ModalsBoxContent
              className="overflow-y-auto"
              style={{
                height: 'calc(100vh - 350px)',
              }}
              ref={userBox}
            >
              {userTree.length > 0 ? (
                <LeftTreeUI
                  treeData={userTree}
                  handleClickUserTree={handleClickUserTree}
                  selectData={selectUserTree}
                  expandedKeys={expandedKeys}
                  defaultValue={defaultValue}
                />
              ) : (
                <NotData fontText="暂无可问答人员/组织" />
              )}
            </ModalsBoxContent>
          ) : (
            <ModalsBoxContent
              className="overflow-y-auto"
              style={{
                height: 'calc(100vh - 330px)',
              }}
            >
              {datasetLoading ? (
                <CircleLoading />
              ) : (
                <>
                  <DatasetAndFunctionTreeUI
                    treeData={datasetTree}
                    handleClickUserTree={handleClickDatasetAndFunctionTree}
                    selectData={selectDatasetAndFunction}
                    expandedKeys={expandedDatasetAndFunction}
                    title="知识库"
                    routerPath="datasets"
                  />

                  {(!isInOrchestrationPage || isEnableFunctionCalling) && (
                    <DatasetAndFunctionTreeUI
                      treeData={functionTree}
                      handleClickUserTree={handleClickDatasetAndFunctionTree}
                      selectData={selectDatasetAndFunction}
                      expandedKeys={expandedDatasetAndFunction}
                      title="数据接口"
                      routerPath="api"
                    />
                  )}

                  {(isEnableNl2sql || isEnableNl2sqlDataset) && (
                    <DatasetAndFunctionTreeUI
                      treeData={nl2sqlTree}
                      handleClickUserTree={handleClickDatasetAndFunctionTree}
                      selectData={selectDatasetAndFunction}
                      expandedKeys={expandedDatasetAndFunction}
                      title="数据库问答"
                      routerPath="nl2sql"
                    />
                  )}
                </>
              )}
            </ModalsBoxContent>
          )}
        </div>

        {appDetail?.appType != AppType.fusion && !isDisableDataset && (
          <div
            className="flex-1 rounded-lg border-[1px] border-solid border-line-3"
            style={{
              maxWidth: `${!isInOrchestrationPage || isEnableFunctionCalling
                ? 'calc(100% - 322px)'
                : 'calc(100% - 252px)'
                }`,
            }}
          >
            {labelKey === '1' ? (
              <>
                {(datasetList.length >= 0 || functionList.length >= 0 || nl2sqlList.length >= 0) && selectUserTree ? (
                  <div className="p-6 pr-0">
                    <div className="pr-6">
                      {(!isInOrchestrationPage || isEnableFunctionCalling || isEnableNl2sqlDataset) && (
                        <Tabs items={tabsItem} onChange={handleTabsValue} activeKey={tabsValue} />
                      )}

                      <div className="flex items-center justify-between">
                        <Button type="primary" onClick={handleInherit}>
                          继承父级权限
                        </Button>

                        <div className="relative">
                          <AutoComplete
                            placeholder={`搜索${tabsItem?.find((item) => item.key === tabsValue)?.label || '知识库'}`}
                            style={{ width: 240 }}
                            value={searchValue}
                            // onChange={(value) => setSearchValue(value)}
                            onSearch={(value) => {
                              setSearchValue(value);
                              handleSearchFn(value, tabsValue);
                            }}
                            // options={treeUIOptions}
                            // onSelect={handleSelect}
                          />
                          <div
                            className="absolute right-2 -translate-y-1/2"
                            style={{ top: 'calc(50% - 1px)' }}
                          >
                            <SvgIcon icon="searchModel" size={16} color="text-text-4" />
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="mt-2 h-full">
                      <TreeUI
                        list={tabsValue === '1' ? datasetList : tabsValue === '2' ? functionList : nl2sqlList}
                        selectKnow={selectUserTree?.resources}
                        handleClickKnow={handleClicTreeUI}
                        tabsKey={tabsValue}
                        expandedKeys={expandedTreeUIKeys}
                        handleClickTreeUITree={handleClickTreeUITree}
                        treeUIRef={functionBox}
                        handleTreeUIOpen={handleTreeUIOpen}
                        openStatus={treeUIOpenAll}
                        contentHeight={
                          !isInOrchestrationPage || isEnableFunctionCalling ? '362px' : '300px'
                        }
                      />
                    </div>
                  </div>
                ) : (
                  <NotData fontText="从左侧选择文件或知识库来设置访问权限" />
                )}
              </>
            ) : (
              <>
                {userTree.length > 0 && selectDatasetAndFunction ? (
                  <div className="p-6 pr-0">
                    <div className="pr-6">
                      <div className="flex items-center justify-between">
                        <Button
                          className="!border-[#1B6DFA] !text-[#1B6DFA]"
                          onClick={modal.update.open}
                        >
                          编辑可问答人员/组织
                        </Button>

                        <div className="relative">
                          <AutoComplete
                            placeholder="搜索人员"
                            onSearch={handleUserSearchFn}
                            // options={userOptions}
                            onSelect={handleUserSelect}
                            style={{ width: 240 }}
                            className="!mb-2 !mt-4"
                          />
                          <div
                            className="absolute right-2 -translate-y-1/2"
                            style={{ top: 'calc(50% + 3px)' }}
                          >
                            <SvgIcon icon="searchModel" size={16} color="text-text-4" />
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="mt-2 h-full">
                      <UserTreeUI
                        list={searchValue.trim() ? filteredUserTree : userTree}
                        selectKnow={selectDatasetAndFunction?.targets}
                        handleClickKnow={handleClickUserTreeUI}
                        expandedKeys={expandedUserTreeUI}
                        handleClickTreeUITree={handleClickUserTreeUIExpandedKeys}
                        defaultValue={defaultValue}
                        treeUIRef={userRightBox}
                        handleTreeUIOpen={handleTreeUserUIOpen}
                        openStatus={treeUserUIOpenAll}
                        contentHeight={
                          !isInOrchestrationPage || isEnableFunctionCalling ? '362px' : '300px'
                        }
                      />
                    </div>
                  </div>
                ) : (
                  <NotData fontText="从左侧选择文件或知识库来设置访问权限" />
                )}
              </>
            )}
          </div>
        )}
      </div>

      <PersonnelModal
        title={`选择问答人员`}
        appId={appId}
        onSubmit={handlePersonnelSubmit}
        isCheckBox={true}
        open={modal.update.isOpen}
        onCancel={modal.update.close}
        confirmLoading={modal.update.isLoading}
        defaultValue={defaultValue}
        disabled={disabledData}
        submitStatus={!(appDetail.review_status === AppStatusEnum.unpublished)}
      />
    </>
  );
};

export default QaPermissionContent;
